import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { useWindowSize, useBreakpoints, breakpointsTailwind } from '@vueuse/core'
import type { ColumnCount, GridColsClass } from '../types/ui'
import { COLUMN_CONFIG } from '../types/ui'

// Toast 相关类型定义
export interface ToastItem {
  id: string
  type: 'success' | 'error' | 'warning' | 'info'
  message: string
  description?: string
  duration?: number
  closable?: boolean
}

export interface ToastOptions {
  type?: 'success' | 'error' | 'warning' | 'info'
  description?: string
  duration?: number
  closable?: boolean
}

export const useUiStore = defineStore('ui', () => {
  const isSidebarCollapsed = ref(false)
  const isDrawerOpen = ref(false)
  const isPerformanceMonitorVisible = ref(false)
  
  // 应用偏好（本地持久化）
  const PREFERENCES_STORAGE_KEY = 'fm_app_preferences_v1'
  const showAiLabel = ref(true)
  const filterAiContent = ref(false)
  
  // Toast 状态管理
  const toasts = ref<ToastItem[]>([])

  // 使用VueUse的响应式hooks
  const { width } = useWindowSize()
  const breakpoints = useBreakpoints(breakpointsTailwind)

  // 响应式计算屏幕尺寸
  const isLarge = computed(() => breakpoints.greater('xl').value) // ≥1280px (5列及以上)
  const isMedium = computed(
    () => breakpoints.greater('md').value && !breakpoints.greater('xl').value,
  ) // 768px-1279px (3列)
  const isSmall = computed(() => !breakpoints.greater('md').value) // <768px (2列)

  // 计算当前屏幕尺寸对应的列数
  const currentColumns = computed<ColumnCount>(() => {
    if (breakpoints.greater('2xl').value) return COLUMN_CONFIG['2xl']
    if (breakpoints.greater('xl').value) return COLUMN_CONFIG.xl
    if (breakpoints.greater('lg').value) return COLUMN_CONFIG.lg
    if (breakpoints.greater('md').value) return COLUMN_CONFIG.md
    if (breakpoints.greater('sm').value) return COLUMN_CONFIG.sm
    return COLUMN_CONFIG.xs // 默认手机
  })

  // 计算网格列数类名
  const gridColsClass = computed<GridColsClass>(() => {
    return 'grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 2xl:grid-cols-5'
  })

  // 计算是否应该显示侧边栏（只有大屏幕显示）
  const shouldShowSidebar = computed(() => {
    return isLarge.value // 只有在大屏幕时才显示侧边栏
  })

  // 计算是否应该显示抽屉（中小屏幕）
  const shouldShowDrawer = computed(() => {
    return !isLarge.value // 在中小屏幕时显示抽屉
  })

  // 监听屏幕大小变化，自动调整侧边栏状态
  watch(
    [isLarge, isMedium, isSmall],
    ([newIsLarge, newIsMedium, newIsSmall], [oldIsLarge, oldIsMedium, oldIsSmall]) => {
      // 从大屏幕切换到中屏幕
      if (newIsMedium && !oldIsMedium) {
        // 中屏幕：收起侧边栏为icon状态，关闭抽屉
        isSidebarCollapsed.value = true
        isDrawerOpen.value = false
      }
      // 从中屏幕切换到大屏幕
      else if (newIsLarge && !oldIsLarge) {
        // 大屏幕：显示展开状态的侧边栏
        isSidebarCollapsed.value = false
        isDrawerOpen.value = false
      }

      // 从中屏幕切换到小屏幕
      if (newIsSmall && !oldIsSmall) {
        // 小屏幕：隐藏侧边栏，关闭抽屉
        isSidebarCollapsed.value = true
        isDrawerOpen.value = false
      }
      // 从小屏幕切换到中屏幕
      else if (newIsMedium && !oldIsMedium) {
        // 中屏幕：收起侧边栏为icon状态，关闭抽屉
        isSidebarCollapsed.value = true
        isDrawerOpen.value = false
      }
    },
    { immediate: true },
  )

  // 初始化偏好（从 localStorage 读取）
  try {
    const saved = localStorage.getItem(PREFERENCES_STORAGE_KEY)
    if (saved) {
      const parsed = JSON.parse(saved)
      if (typeof parsed.showAiLabel === 'boolean') showAiLabel.value = parsed.showAiLabel
      if (typeof parsed.filterAiContent === 'boolean') filterAiContent.value = parsed.filterAiContent
    }
  } catch (e) {
    // ignore parse errors
  }

  // 持久化偏好
  watch([showAiLabel, filterAiContent], ([newShowAiLabel, newFilterAiContent]) => {
    const payload = {
      showAiLabel: newShowAiLabel,
      filterAiContent: newFilterAiContent,
    }
    try {
      localStorage.setItem(PREFERENCES_STORAGE_KEY, JSON.stringify(payload))
    } catch (e) {
      // ignore set errors
    }
  }, { immediate: false })

  // 切换侧边栏状态
  const toggleSidebar = () => {
    if (shouldShowSidebar.value) {
      // 大屏幕：控制侧边栏展开/折叠
      isSidebarCollapsed.value = !isSidebarCollapsed.value
    } else {
      // 中小屏幕：控制抽屉打开/关闭
      isDrawerOpen.value = !isDrawerOpen.value
    }
  }

  // 设置侧边栏状态
  const setSidebar = (collapsed: boolean) => {
    isSidebarCollapsed.value = collapsed
  }

  // 打开抽屉
  const openDrawer = () => {
    isDrawerOpen.value = true
  }

  // 关闭抽屉
  const closeDrawer = () => {
    isDrawerOpen.value = false
  }

  // 设置性能监控可见性
  const setPerformanceMonitorVisible = (visible: boolean) => {
    isPerformanceMonitorVisible.value = visible
  }

  // Toast 相关方法
  const addToast = (message: string, options: ToastOptions = {}) => {
    const id = `toast-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
    const toast: ToastItem = {
      id,
      type: options.type || 'info',
      message,
      description: options.description,
      duration: options.duration ?? 5000,
      closable: options.closable ?? true
    }
    
    toasts.value.push(toast)
    
    // 如果设置了自动关闭，则设置定时器
    if (toast.duration && toast.duration > 0) {
      setTimeout(() => {
        removeToast(id)
      }, toast.duration)
    }
    
    return id
  }

  const removeToast = (id: string) => {
    const index = toasts.value.findIndex(toast => toast.id === id)
    if (index > -1) {
      toasts.value.splice(index, 1)
    }
  }

  const clearToasts = () => {
    toasts.value = []
  }

  // 便捷方法
  const showSuccess = (message: string, options?: Omit<ToastOptions, 'type'>) => {
    return addToast(message, { ...options, type: 'success' })
  }

  const showError = (message: string, options?: Omit<ToastOptions, 'type'>) => {
    return addToast(message, { ...options, type: 'error' })
  }

  const showWarning = (message: string, options?: Omit<ToastOptions, 'type'>) => {
    return addToast(message, { ...options, type: 'warning' })
  }

  const showInfo = (message: string, options?: Omit<ToastOptions, 'type'>) => {
    return addToast(message, { ...options, type: 'info' })
  }

  return {
    // 状态
    isSidebarCollapsed,
    isDrawerOpen,
    isPerformanceMonitorVisible,
    showAiLabel,
    filterAiContent,
    toasts,

    // 屏幕尺寸检测
    isLarge,
    isMedium,
    isSmall,

    // 列数计算
    currentColumns,
    gridColsClass,

    // 显示控制
    shouldShowSidebar,
    shouldShowDrawer,

    // 方法
    toggleSidebar,
    setSidebar,
    openDrawer,
    closeDrawer,
    setPerformanceMonitorVisible,
    
    // Toast 方法
    addToast,
    removeToast,
    clearToasts,
    showSuccess,
    showError,
    showWarning,
    showInfo,
  }
})
